from pyvisml import VisML

import sys

def usage():
    print('\nUSAGE: python remove_dups.py infile outfile\n\n')
    sys.exit()

if len(sys.argv) != 3:
    usage()

infile  = sys.argv[1]
outfile = sys.argv[2]

# Creates a new object and parses the existing tree into a VisMLTree object
tree = VisML.VisMLTree(infile)

# We first locate all duplicates, find their parent node names, and remove the duplicate node
node_dup_pairs = {}
for node in tree.nodes:
    if node.duplicates:
        for dup in node.duplicates:
            node_dup_pairs[dup.uid] = node.name
            tree.remove_node(dup)

# Now, we locate all metanodes and replace duplicate child names with the parent node names
for node in tree.nodes:
    if node.ismetanode:
        if node.children is not None:
            
            children = node.children
            for i in xrange(len(children)):
                child_name = children[i]

                if child_name in node_dup_pairs:
                    node.remove_child(child_name)
                    node.add_child(node_dup_pairs[child_name])

# Write the tree to our outfile
tree.write(outfile)
